package net.howson.phil.datahiding.stream;

import java.io.IOException;
import java.io.OutputStream;

public class BitWidthOutputStream extends OutputStream {

	private final OutputStream delegate;
	private final int width;
	private final int mask;
	private int cursor;
	private int value;

	public BitWidthOutputStream(OutputStream delegate, int width) {
		this.delegate = delegate;
		this.width = width;
		this.mask = BitWidthStreamUtils.createMask(width);

	}

	@Override
	public void write(int b) throws IOException {
		value |= (b & mask) << (cursor);		
		if ((cursor+=width) == 8) {
			delegate.write(value);
			cursor = 0;
			value = 0;
		}

	}

	@Override
	public void close() throws IOException {
		if (cursor!=0) {
			delegate.write(value);
		}
		delegate.close();
		super.close();
	}
}
